// orderConfirm.js
const regeneratorRuntime = require('../../lib/runtime');
const Api = require('../../utils/api.js');
const wx = require('../../lib/wx');
const wxapp = require('../../lib/wxapp');
const Util = require('../../utils/util.js');

// 获取应用实例
const app = getApp();
Page({
  data: {
    noAddress: true,
    isImported: false,
    goodsInfo:[],
    buyType:2,
    order_attr:null,
    orderInfo: [{
      color: '',
      size: '',
      productNum: '',
      price: '',
      logo: 'http://www.haba.com.cn/images/logo3.png',
      shop: 'HABA',
      img: 'http://www.haba.com.cn/UploadFiles/ProductImg/110df2c5-447f-4d46-863e-75d059b47e48.png',
      express: '直邮中国',
      expressIcon: '../../images/icon_flag_china.png',
      productInfo: 'HABA 日本无添加主义丝滑泡沫洁面皂 80g',
      freight: '8.00',
    }],
    userInfo: {
      name: '隔壁老王',
      address: '北京-北京市-东城区 隔壁路老王街',
      phone: '13858588858',
    },
    tariffGuarantee: false,
    purchaseNotice: true,
    modalHide: true,
    total:0,
    couponTotal:0,
    coupon:{
      couponId:'',
      couponTitle:''
    }
  },

  goToAddress: wxapp.handler(function* goToAddress(next){
    const url = '../myAddress/myAddress';
    wx.navigateTo({
      url,
    });

    yield next;
  }),

  goToCoupon: wxapp.handler(function* goToCoupon(next){
    const url = '../selectCoupon/selectCoupon';
    wx.navigateTo({
      url,
    });

    return;

    yield next;
  }),

  goToPay: wxapp.handler(function* goToPay(next,e) {
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    const url = '../login/login';
    if (!token) {
      wx.reLaunch({
        url,
      });
    }
    const goodsInfo = this.data.goodsInfo;
    var getPlaceOrder = Api.getPlaceOrder();
    var wxPay = Api.wxPay();
    
    var address = wx.getStorageSync('choseAddress');
    if(address){
      var address_id = address.id;
    }else{
      var address_id = 0;
    }
    var coupon_id = e.detail.value.coupon_id;
    //console.log(address);
    var that = this;

    wx.request({
      url: getPlaceOrder,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: {
        token: token,
        goodsInfo: JSON.stringify(goodsInfo),
        remarks:e.detail.value.message,
        address_id:address_id ,
        price_sum: e.detail.value.price_sum,
        buyType:that.data.buyType,
        coupon_id: coupon_id,
        attr: that.data.order_attr
      },
      complete: function (res) {
        if (res.data.status == 1) {
          wx.showToast({
            title: '下单成功',
            icon: 'success',
            duration: 2000,
          });
          
          wx.request({
            url: wxPay,
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            method: 'POST',
            data: {
              order_id: res.data.data,
              token: token
            },
            complete: function (res) {
              console.log(res);
              if (res.data.status != 0) {
                var order = res.data.data;
                if (order.nonceStr) {
                  wx.requestPayment({
                    timeStamp: order.timeStamp,
                    nonceStr: order.nonceStr,
                    package: order.package,
                    signType: 'MD5',
                    paySign: order.paySign,
                    success: function (res) {
                      wx.showToast({
                        title: "支付成功!",
                        duration: 2000,
                        complete: function () {
                          setTimeout(function () {
                            wx.navigateTo({
                              url: '../me/me',
                            });
                          }, 3000);
                        }
                      });

                    },
                    fail: function (res) {
                      wx.showToast({
                        title: res,
                        image: '../../images/error.png',
                        duration: 3000
                      })
                    },
                    complete: function (res) {
                      if (res.errMsg == 'requestPayment:ok') {
                        wx.showToast({
                          title: "支付成功!",
                          duration: 2000,
                          complete: function () {
                            setTimeout(function () {
                              wx.navigateTo({
                                url: '../me/me',
                              });
                            }, 3000);
                          }
                        });
                      }
                    }
                  })
                } else {
                  wx.showToast({
                    title: '系统错误',
                    image: '../../images/error.png',
                    duration: 3000
                  })
                }
              } else {
                wx.showToast({
                  title: res.data.msg,
                  image: '../../images/error.png',
                  duration: 3000
                })
              }
            }
          });



        } else {
          wx.showToast({
            title: res.data.msg,
            image: '../../images/error.png',
            duration: 2000,
          });
        }
      }
    });

    yield next;
  }),

  purchaseNoticeChange: wxapp.handler(function* purchaseNoticeChange(next, e){
    const pageData = this.data;
    let purchaseNotice = pageData.purchaseNotice;
    if(purchaseNotice){
      purchaseNotice = false;
    } else{
      purchaseNotice = true;
    }
    this.setData({
      purchaseNotice,
    });

    yield next;
  }),

  tariffGuaranteeChange: wxapp.handler(function* tariffGuaranteeChange(next, e){
    const pageData = this.data;
    let tariffGuarantee = pageData.tariffGuarantee;
    if(tariffGuarantee){
      tariffGuarantee = false;
    } else{
      tariffGuarantee = true;
    }
    this.setData({
      tariffGuarantee,
    });

    yield next;
  }),

  showTips: wxapp.handler(function* showTips(next){
    let modalHide = this.data.modalHide;
    if(modalHide){
      modalHide = false;
    } else{
      modalHide = true;
    }
    this.setData({
      modalHide,
    });

    yield next;
  }),

  hideTips: wxapp.handler(function* hideTips(next){
    this.setData({
      modalHide: true,
    });

    yield next;
  }),

  onShow: wxapp.handler(function* onShow(next) {
    let address = wx.getStorageSync('choseAddress');
    if(address){
      this.setData({
        noAddress:false,
        userInfo:address
      });
    }

    // console.log(this.data.coupon);



    yield next;
  }),

  onLoad: wxapp.handler(function* onLoad(next, options) {
    const submitValue = options;
    const info = JSON.parse(submitValue.goodsInfo);
    const buyType = submitValue.buyType;
    const goodsInfo = this.data.goodsInfo;
    //goodsInfo.push(info);
    for(var i=0;i<info.length;i++) {
      info[i].num = info[i].goods_num;
      info[i].goods_price = info[i].price_new;
      goodsInfo.push(info[i]);
    }

    var orderInfo = [];
    var total = this.data.total;
    for(var i=0;i<info.length;i++) {
      total += info[i].price * info[i].productNum;
      console.log(info[i].spec);
      if(!info[i].spec) {
        var spec = '';
        for (var j = 0; j <= 10; j++) {
          var key = 'spec' + j;
          if (!info[i][key]) {
            break;
          }
          var sstr = info[i][key].split("-"); //字符分割
          spec += sstr[1] + ':' + sstr[2] + ' ';
        }
        info[i].spec = spec;
      }
      orderInfo.push(info[i]);
    }

    // console.log(info);
    //  console.log(orderInfo);

    this.setData({
      orderInfo: orderInfo,
      goodsInfo: goodsInfo,
      total:total,
      couponTotal:total,
      buyType:buyType,
      order_attr: submitValue.attr
    });

    yield next;
  }),

});
